{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 230519 十九中\n",
    "图形学 04 | 动态物体追踪 `->背景差分法`\n",
    "\n",
    "> 创意：让保安叔叔歇一歇 智能清校精灵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "camera = cv2.VideoCapture(0)\n",
    "knn = cv2.createBackgroundSubtractorKNN()\n",
    "kernel = np.ones((20,20))\n",
    "\n",
    "while True:\n",
    "    ok,image = camera.read()\n",
    "    if ok:\n",
    "        new = knn.apply(image)\n",
    "        blur = cv2.GaussianBlur(new,(15,15),3)\n",
    "        _,binary = cv2.threshold(blur,100,255,8)\n",
    "        dilate = cv2.dilate(binary,kernel)\n",
    "        cnts,_ = cv2.findContours(dilate,3,2)\n",
    "        n = len(cnts)\n",
    "        cv2.putText(image,str(n),(20,40),0,1,(0,255,0),2)\n",
    "        # imshow\n",
    "        cv2.imshow('new',new)\n",
    "        cv2.imshow('blur',blur)\n",
    "        cv2.imshow('binary',binary)\n",
    "        cv2.imshow('dilate',dilate)\n",
    "        cv2.imshow('image',image)\n",
    "        if cv2.waitKey(10) > 0:\n",
    "            break\n",
    "cv2.destroyAllWindows()\n",
    "camera.release()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
